import { ref, computed } from 'vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore'

// VIP到期提醒相关状态
const vipReminderVisible = ref(false)
const remainingDays = ref(0)
const lastReminderTime = ref<number>(0)

// 稍后提醒的间隔时间（小时）
const REMIND_LATER_HOURS = 24

export function useVipExpiryReminder() {
	const loginUserStore = useLoginUserStore()

	// 检查是否需要显示VIP到期提醒
	const checkVipExpiry = async () => {
		try {
			// 如果用户未登录，不需要检查
			if (!loginUserStore.isLoggedIn()) {
				return
			}

			// 如果用户不是VIP，不需要检查
			if (!loginUserStore.loginUser?.isVip) {
				return
			}

			// 从loginUser中获取VIP剩余天数
			remainingDays.value = loginUserStore.loginUser?.vipRemainingDays || 0

			// 判断是否需要提醒
			// 剩余天数在 -3 到 7 天之间时提醒
			const shouldRemind = remainingDays.value >= -3 && remainingDays.value <= 7

			if (shouldRemind) {
				// 检查是否在"稍后提醒"的冷却期内
				const now = Date.now()
				const coolDownEnd = lastReminderTime.value + REMIND_LATER_HOURS * 60 * 60 * 1000

				if (now > coolDownEnd) {
					showVipExpiryReminder()
				}
			}
		} catch (error) {
			console.error('检查VIP到期状态失败:', error)
		}
	}

	// 显示VIP到期提醒
	const showVipExpiryReminder = () => {
		vipReminderVisible.value = true
	}

	// 隐藏VIP到期提醒
	const hideVipExpiryReminder = () => {
		vipReminderVisible.value = false
	}

	// 稍后提醒
	const remindLater = () => {
		lastReminderTime.value = Date.now()
		// 可以将时间存储到localStorage中，以便跨会话保持
		localStorage.setItem('vip_reminder_last_time', lastReminderTime.value.toString())
		hideVipExpiryReminder()
	}

	// 初始化时从localStorage读取上次提醒时间
	const initReminderState = () => {
		const savedTime = localStorage.getItem('vip_reminder_last_time')
		if (savedTime) {
			lastReminderTime.value = parseInt(savedTime, 10)
		}
	}

	// 计算提醒文本
	const reminderText = computed(() => {
		if (remainingDays.value > 0) {
			return `您的VIP会员将在 ${remainingDays.value} 天后到期`
		} else if (remainingDays.value === 0) {
			return '您的VIP会员将在今天到期'
		} else {
			return `您的VIP会员已过期 ${Math.abs(remainingDays.value)} 天`
		}
	})

	// 获取提醒状态颜色
	const getReminderColor = computed(() => {
		if (remainingDays.value <= 0) {
			return '#ff4d4f' // 红色：已过期
		} else if (remainingDays.value <= 3) {
			return '#ff9800' // 橙色：即将到期
		} else {
			return '#1890ff' // 蓝色：正常提醒
		}
	})

	// 初始化
	initReminderState()

	return {
		// 状态
		vipReminderVisible,
		remainingDays,
		reminderText,
		getReminderColor,

		// 方法
		checkVipExpiry,
		showVipExpiryReminder,
		hideVipExpiryReminder,
		remindLater,
		initReminderState,
	}
}

// 全局实例变量，延迟初始化
let globalVipReminderInstance: ReturnType<typeof useVipExpiryReminder> | null = null

// 获取全局VIP提醒实例，懒加载方式
export function getGlobalVipReminder() {
	if (!globalVipReminderInstance) {
		globalVipReminderInstance = useVipExpiryReminder()
	}
	return globalVipReminderInstance
}
